#!/bin/sh

CD=$(pwd)
cd "$(dirname "$0")"
WORKDIR=$(pwd)
cd $CD

[ -f /etc/init.d/functions ] && {
    . /etc/init.d/functions
} || {
    . $WORKDIR/etc/functions
}

EXPPIDFILE="$WORKDIR/log/exp.pid"
EXPLOGFILE="$WORKDIR/log/exp.log"

printExpErr() {
    tail -n30 $EXPLOGFILE >&2
}	

runExp() {
    { nohup npm start \
        1>$EXPLOGFILE \
        2>&1 &
    } \
    && echo $! >$EXPPIDFILE \
    && {
        while ps -p $(cat $EXPPIDFILE) >/dev/null; do
            if grep -q 'Starting up http-server' $EXPLOGFILE >/dev/null; then
                return 0
            else
                sleep 1
            fi
        done
    }
    return 1
}

startExp() {
    if [ ! -f $EXPPIDFILE ]; then
        action 'Explorer starting' runExp || {
            printExpErr
            return 1
        }
    else
        rm -f $EXPPIDFILE && action 'Explorer forced restarting' runExp || {
            printExpErr
            return 1
        }
    fi
}

killExp() {
    kill -15 $(cat $EXPPIDFILE)
    while ps -p $(cat $EXPPIDFILE) >/dev/null; do
        sleep 1
    done
    rm -f $EXPPIDFILE
}

stopExp() {
    if [ ! -f $EXPPIDFILE ]; then
        printf 'Explorer is not running'
        success
        echo ''
    else
        action 'Explorer stopping' killExp || printExpErr
    fi
}


case "$1" in
    start)
        startExp || exit 1
        ;;
    stop)
        stopExp
        ;;
    restart)
        stopExp && startExp || exit 1
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac
